import { Asset, Constructor, AssetManager, assetManager, _decorator } from 'cc';

/** 
 * 资源管理器 
 */
export class ResManager {

    /**
     * 加载资源包
     * @param bundleName 资源包名称
     * @param cb 可选回调
     */
    loadBundle(bundleName: string, cb?: (bundle: AssetManager.Bundle | null) => void) {
        assetManager.loadBundle(bundleName, (e, bundle) => {
            cb && cb(bundle);
        });
    }

    /**
     * 异步加载资源包
     * @param bundleName 资源包名称
     * @returns 
     */
    loadBundleAsync(bundleName: string): Promise<AssetManager.Bundle> {
        return new Promise<AssetManager.Bundle>(rs => this.loadBundle(bundleName, rs))
    }

    /**
     * 加载资源
     * @param bUrl 资源路径
     * @param type 资源类型
     * @param cb 回调函数
     */
    loadAsset<T extends Asset>(bUrl: IBundleUrl, type: Constructor<T> | null, cb: (asset: T | null) => void) {
        assetManager.loadBundle(bUrl.bundleName, (e, bundle) => {
            bundle.load(bUrl.assetName, type, (err, _asset) => {
                if (err) {
                    console.error(err);
                    return cb(null);
                }
                cb(_asset)
            })
        })
    }

    /**
     * 异步加载资源
     * @param bUrl 资源路径
     * @param type 资源类型
     * @returns 
     */
    loadAssetAsync<T extends Asset>(bUrl: IBundleUrl, type: Constructor<T> | null) {
        return new Promise<T>(rs => this.loadAsset(bUrl, type, rs as any))
    }

    /**
     * 获取资源
     * @param bUrl 资源路径
     * @param type 资源类型
     * @returns 
     */
    getAsset<T extends Asset>(bUrl: IBundleUrl, type?: Constructor<T> | null): T {
        let assetBundle = assetManager.getBundle(bUrl.bundleName);
        return assetBundle.get(bUrl.assetName, type)
    }
    
}